import { memo, useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import moment from 'moment';
import { Popup, NavBar, Form, CheckList, DatePicker, Input, Toast } from 'antd-mobile';
import MemberSelect from '@inbiz/basic/WapMemberSelect';
import { setFutureTask, setTask, getApplyList, getApplyCategory } from './service';
import { TextWidget, getMessage } from '@inbiz/react';
import { useInbizRouter } from '@inbiz/hooks';
import './index.less';

const ProcessSetAssign = memo((props: any) => {
  const { userInfo } = props;
  const [applyList, $applyList] = useState([]);
  const [applyCatogory, $applyCatogory] = useState([]);
  const now = new Date();
  const [form] = Form.useForm();
  const router = useInbizRouter();
  const _query = router.location.query;
  const type = _query.type;
  const ids = _query.ids;
  const [startVisible, $startVisible] = useState(false);
  const [endVisible, $endVisible] = useState(false);
  const [chooseProcess, $chooseProcess] = useState('');
  const [processItemName, $processItemName] = useState('');
  const [processVisible, $processVisible] = useState(false);
  const [memberVisible, $memberVisible] = useState(false);
  const [selected, $selected] = useState<any[]>([]);

  const searchApplyList = (value?: string) => {
    getApplyList({ userId: userInfo.ID, pageIndex: 1, pageSize: 50 }).then((res) => {
      $applyList(res.data.rows);
    });
  };
  useEffect(() => {
    if (userInfo?.ID) {
      searchApplyList();
      getApplyCategory({ userId: userInfo.ID }).then((res) => {
        if (res.GroupData) {
          $applyCatogory(res.GroupData);
        }
      });
    }
  }, [userInfo]);
  const selectedPerson = (selecteds: any[]) => {
    $selected(selecteds);
    $memberVisible(false);
    form.setFieldsValue({ sendto: selecteds.map((item) => item.name).join(',') });
  };
  const confirmAssign = () => {
    form.validateFields().then((res) => {
      if (type == 1) {
        setTask({
          delegateUserId: selected.map((item) => item.id).join(','),
          taskIds: ids,
        }).then((res) => {
          if (res.code == '200') {
            Toast.show({ content: res.message });
            router.goBack();
          } else {
            Toast.show({ content: res.message });
          }
        });
      } else {
        setFutureTask({
          assignee: userInfo.ID,
          attorney: selected.map((item) => item?.id).join(','),
          stratTime: moment(res.startTime).format('YYYY-MM-DD') + ' 00:00:00',
          endTime: moment(res.endTime).format('YYYY-MM-DD') + ' 23:59:59',
          processKey: chooseProcess?.[0],
          status: '1',
        }).then((res) => {
          if (res.code == '200') {
            Toast.show({ content: res.message });
            router.goBack();
          } else {
            Toast.show({ content: res.message });
          }
        });
      }
    });
  };
  const chooseProcessItem = (value: string[]): void => {
    const name = applyList.find((item) => item.Process_Key == value)?.Process_Name || '';
    $chooseProcess(value);
    $processItemName(name);
  };
  // return createPortal(
  return (
    <div className={'processSetAssign'}>
      {!memberVisible && (
        <>
          <NavBar
            onBack={() => {
              router.goBack();
            }}
            backArrow={
              <a>
                <TextWidget>global.cancel</TextWidget>
              </a>
            }
            right={
              <a onClick={confirmAssign}>
                <TextWidget>global.sure</TextWidget>
              </a>
            }
          >
            {type == 2
              ? getMessage('processCenter.setWillAssign')
              : getMessage('processCenter.setCurrentAssign')}
          </NavBar>
          <Form form={form} layout="horizontal">
            {type == 2 && (
              <Form.Item
                label={getMessage('processCenter.selectProcess')}
                name="process"
                onClick={() => $processVisible(true)}
                rules={[{ required: true, message: getMessage('processCenter.selectProcesstips') }]}
              >
                <Input readOnly placeholder={getMessage('processCenter.placeholder')} />
              </Form.Item>
            )}
            <Form.Item
              label={getMessage('processCenter.assignto')}
              name="sendto"
              onClick={() => $memberVisible(true)}
              rules={[{ required: true, message: getMessage('processCenter.pickAssigner') }]}
            >
              <Input readOnly placeholder={getMessage('processCenter.placeholder')} />
            </Form.Item>
            {type == 2 && <Form.Header />}
            {type == 2 && (
              <Form.Item
                name="startTime"
                label={getMessage('processCenter.starttime')}
                onClick={() => {
                  $startVisible(true);
                }}
                trigger="onConfirm"
                rules={[{ required: true, message: getMessage('processCenter.selectstarttime') }]}
              >
                <DatePicker
                  visible={startVisible}
                  onClose={() => {
                    $startVisible(false);
                  }}
                  min={now}
                >
                  {(value) => {
                    return value ? (
                      moment(value).format('YYYY-MM-DD')
                    ) : (
                      <span style={{ color: '#ccc' }}>
                        {getMessage('processCenter.placeholder')}
                      </span>
                    );
                  }}
                </DatePicker>
              </Form.Item>
            )}
            {type == 2 && (
              <Form.Item
                name="endTime"
                label={getMessage('processCenter.endTime')}
                onClick={() => {
                  $endVisible(true);
                }}
                trigger="onConfirm"
                rules={[
                  { required: true, message: getMessage('processCenter.selectendTime') },
                  {
                    validator: function (rule, value, callback): any {
                      const st = form.getFieldValue('startTime');
                      if (moment(value).valueOf() < moment(st).valueOf()) {
                        return Toast.show(getMessage('processCenter.reselectTime'));
                      }
                      callback();
                    },
                  },
                ]}
              >
                <DatePicker
                  visible={endVisible}
                  onClose={() => {
                    $endVisible(false);
                  }}
                  onConfirm={(value) => {
                    const st = form.getFieldValue('startTime');
                    if (moment(value).valueOf() < moment(st).valueOf()) {
                      return Toast.show(getMessage('processCenter.reselectTime'));
                    }
                  }}
                  min={now}
                >
                  {(value) => {
                    return value ? (
                      moment(value).format('YYYY-MM-DD')
                    ) : (
                      <span style={{ color: '#ccc' }}>
                        {getMessage('processCenter.placeholder')}
                      </span>
                    );
                  }}
                </DatePicker>
              </Form.Item>
            )}
          </Form>
        </>
      )}
      <Popup
        visible={processVisible}
        onMaskClick={() => $processVisible(false)}
        bodyStyle={{ height: 500 }}
        bodyClassName={'process-center-h5-popup-select'}
      >
        <NavBar
          onBack={() => {
            $chooseProcess('');
            $processVisible(false);
          }}
          backArrow={
            <a>
              <TextWidget>global.cancel</TextWidget>
            </a>
          }
          right={
            <a
              onClick={() => {
                form.setFieldsValue({ process: processItemName });
                $processVisible(false);
              }}
              style={{ fontSize: 24 }}
            >
              <TextWidget>global.sure</TextWidget>
            </a>
          }
        />
        {/* <SearchBar clearable onSearch={searchApplyList} placeholder="请输入关键词搜索流程" /> */}
        <CheckList onChange={chooseProcessItem} className={'processList'}>
          {applyList.map((item: { Process_Key: string; Process_Name: string }) => {
            return (
              <CheckList.Item key={item.Process_Key} value={item.Process_Key}>
                {item.Process_Name}
              </CheckList.Item>
            );
          })}
        </CheckList>
      </Popup>
      {memberVisible && (
        <MemberSelect
          onCancel={() => $memberVisible(false)}
          onOk={selectedPerson}
          tabs={['user']}
          selected={selected}
          multiple={false}
        />
      )}
    </div>
    // document.querySelector('#processcenterContainer') as Element,
  );
});
export default ProcessSetAssign;
